package com.rtsapp.agent.rules;

import com.rtsapp.server.logger.Logger;
import com.rtsapp.server.logger.LoggerFactory;

/**
 * Created by liwang on 17-3-23.
 * <p>
 * 热修复 ClassName 的规则
 */
public class ClassNameCodex {

    private static final Logger LOG = LoggerFactory.getLogger( ClassNameCodex.class );

    private final ClassNameCodexEnum codexEnum;
    private final String[] params;
    // true: className需要包含params
    // false: className需要不包含params
    private final boolean include;


    public ClassNameCodex( ClassNameCodexEnum codexEnum, String... params ) {
        this.codexEnum = codexEnum;
        this.params = params;
        this.include = true;
    }


    /**
     * 判断此规则是否可用
     *
     * @return
     */
    public boolean isValid( ) {
        if ( codexEnum == null ) {
            return false;
        }

        switch ( codexEnum ) {

            case ALL: {
                return true;
            }

            case BY_NAMES:
            case BY_PACKAGES: {
                return !AgentUtils.isEmpty( params );
            }

            default: {
                return false;
            }
        }
    }

    public static boolean isValid( ClassNameCodex... codexs ) {
        if ( AgentUtils.isEmpty( codexs ) ) {
            return false;
        }

        for ( ClassNameCodex codex : codexs ) {
            if ( !codex.isValid( ) ) {
                return false;
            }
        }

        return true;
    }

    public boolean testClassName( String className ) {
        if ( AgentUtils.isEmpty( className ) ) {
            return false;
        }

        switch ( codexEnum ) {

            case ALL: {
                return true;
            }

            // 更新指定的.class
            case BY_NAMES: {
                for ( String codexStr : params ) {
                    if ( className.equals( codexStr ) ) {
                        return true;
                    }
                }

                break;
            }

            // 更新指定包名下的所有.class
            case BY_PACKAGES: {
                for ( String codexStr : params ) {
                    if ( className.startsWith( codexStr ) ) {
                        return true;
                    }
                }

                break;
            }

            default: {
                break;
            }
        }

        return false;
    }

    public static boolean testClassName( String className, ClassNameCodex... codexs ) {
        if ( AgentUtils.isEmpty( codexs ) || AgentUtils.isEmpty( className ) ) {
            return false;
        }

        for ( ClassNameCodex codex : codexs ) {
            if ( codex.testClassName( className ) ) {
                return true;
            }
        }

        return false;
    }
}
